<template>
  <div>
    <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body :close-on-click-modal="false" v-dialogDrag>
      <div class="app-container">
        <el-form :inline="true" :model="queryParams" label-width="98px" ref="queryForm" size="small">
          <el-form-item label="工程名称" prop="gongchengName">
            <el-input v-model="queryParams.gongchengName" placeholder="请输入工程名称" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="交货日期" prop="deliveryTime">
            <el-date-picker clearable v-model="queryParams.deliveryTime" type="date" value-format="yyyy-MM-dd"
              placeholder="请选择交货日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="产品编码" prop="goodsCode">
            <el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入产品编码" v-model="queryParams.goodsCode" />
          </el-form-item>
          <el-form-item label="产品名称" prop="goodsName">
            <el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入产品名称" v-model="queryParams.goodsName" />
          </el-form-item>
          <el-form-item label="产品型号" prop="goodModel">
            <el-input @keyup.enter.native="handleQuery" clearable placeholder="请输入产品型号" v-model="queryParams.goodModel" />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery" icon="el-icon-search" size="mini" type="primary">搜索</el-button>
            <el-button @click="resetQuery" icon="el-icon-refresh" size="mini">重置</el-button>
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出
            </el-button>
          </el-form-item>
        </el-form>
        <div v-if="selectedRows.length > 0">
          <span>已勾选数量合计: {{selectedRows.reduce((acc, row) => acc + row.orderCount, 0)}}</span>
        </div>
        <el-table show-summary :summary-method="totalOutYear" v-loading="loading" :data="dataList" ref="table" :max-height="tableMaxHeight" border @selection-change="handleSelectionChange"
          @sort-change="handleSortChange">
          <el-table-column type="selection" width="55" align="center"/>
          <!--<el-table-column sortable label="单据号" align="center" prop="nos"/>-->
          <el-table-column sortable label="订单编号" align="center" prop="projectNo" show-overflow-tooltip />
          <el-table-column sortable label="工程名称" align="center" prop="gongchengName" show-overflow-tooltip />
          <el-table-column sortable align="center" label="客户名称" prop="customerName" />
          <el-table-column sortable align="center" label="业务员" prop="salesmanName" />
          <el-table-column sortable label="交货日期" align="center" prop="deliveryTime" />
          <el-table-column sortable label="中标价" align="center" prop="goodsTaxUnitPrice" />
          <el-table-column sortable label="产品编码" align="center" prop="goodsCode" />
          <el-table-column sortable label="产品名称" align="center" prop="goodsName" show-overflow-tooltip />
          <el-table-column sortable label="产品型号" align="center" prop="goodModel" show-overflow-tooltip />
          <el-table-column sortable label="产品状态" align="center" prop="status">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.goods_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column sortable label="产品类型" align="center" prop="type" />
          <el-table-column sortable label="计量单位" align="center" prop="unit" />
          <el-table-column sortable label="是否自制" align="center" prop="isdo">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.isdo" :value="scope.row.isdo" />
            </template>
          </el-table-column>
          <!-- <el-table-column sortable align="center" label="订单数量" prop="orderCount" />
          <el-table-column sortable align="center" label="锁定数量" prop="lockCount" /> -->
          <el-table-column sortable align="center" label="请购/自制数量" prop="pleaseBuyCount" />
          <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
          <el-table-column label="操作"  align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <!-- {{ showTrue +"和" +scope.row.status}} -->
            <el-button size="mini" type="text" icon="el-icon-info" v-show="scope.row.type == '产品' && (scope.row.status == '2' || scope.row.status == '1' ||
            scope.row.status == '11' || scope.row.status == '6' || scope.row.status == '38')"
                       v-hasPermi="['develop:GoodsSaleDo:kuguanxiugai']"  @click="elseHandleEdit(scope.row)">库管修改
            </el-button>
            <el-popconfirm :title="`确认退回产品吗？`" @confirm="handleSubmitToLvyue(scope.row)" v-show="( scope.row.status == '38' || scope.row.status == '2'|| scope.row.status == '1'
              || scope.row.status == '11' || scope.row.status == '6') && scope.row.type == '产品' "
                           v-hasPermi="['develop:GoodsSaleDo:kuguantuihui']"   style="margin-left: 10px;">
              <el-button slot="reference" size="mini" type="text" icon="el-icon-delete">库管退回</el-button>
            </el-popconfirm>
            <!--<el-button size="mini" type="text" icon="el-icon-info"
            v-if="scope.row.type == '其他'  && showTrue == 2" @click="elseHandleEdit(scope.row)">其他修改
            </el-button>
            <el-popconfirm :title="`确认删除 ` + scope.row.goodsName + ` 数据项？`" @confirm="handleDelete(scope.row)"
                       style="margin-left: 10px;">
              <el-button slot="reference" size="mini" type="text" icon="el-icon-delete"  v-if="!scope.row.projectNo  && showTrue == 2">删除产品
              </el-button>
            </el-popconfirm>-->

            <el-popconfirm :title="`确认删除 ` + scope.row.goodsName + ` 数据项？`" @confirm="handleDelete(scope.row)"
                           v-show="scope.row.type === 'u8导入' && scope.row.status ==='33'" style="margin-left: 10px;">
              <el-button slot="reference" size="mini" type="text" icon="el-icon-delete">删除产品
              </el-button>
            </el-popconfirm>
            
            <el-button size="mini" type="text" icon="el-icon-info" v-hasPermi="['develop:GoodsSaleDo:jishuxiugai']"
                       v-show="(scope.row.status == '5' || scope.row.status == '3' ||  scope.row.status == '4' || scope.row.status == '39'
                       /*|| scope.row.status == '11' || scope.row.status == '6'*/ )" @click="handleEdit(scope.row)">技术修改
            </el-button>
            <el-popconfirm :title="`确认退回产品吗？`" @confirm="handleSubmitToKuguan(scope.row)"
                           v-show="( scope.row.status == '5' || scope.row.status =='3' || scope.row.status == '4' || scope.row.status == '39'
                          /* ||  scope.row.status == '11' || scope.row.status == '6'*/ ) && scope.row.type == '产品' " style="margin-left: 10px;">
                <el-button slot="reference" size="mini" type="text" icon="el-icon-delete" v-hasPermi="['develop:GoodsSaleDo:jishutuihui']" >技术退回</el-button>
            </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" />
      </div>
    </el-dialog>

    <!-- 添加 editPleaseBuyForm 弹窗 -->
      <edit-please-buy-form  ref="EditPleaseBuyFormList" @ok="getList" @close="editOpen = false" />
      <else-edit-please-buy-form  ref="ElseEditPleaseBuyFormList" @ok="getList" @close="editOpen = false" />
  </div>
</template>

<script>
import { downloadFile, getAction, accAdd,deleteAction,updateAction } from '@/api/manage'
import EditPleaseBuyForm from '@/views/develop/pleaseBuy/module/editPleaseBuyFormList.vue'
import ElseEditPleaseBuyForm from '@/views/develop/pleaseBuy/module/elseEditPleaseBuyFormList.vue'

export default {
  name: "PleaseBuyFormList",
  dicts: ['fund_callback', 'sale_type', 'yes_no', 'isdo', 'goods_status'],
  components: {
    EditPleaseBuyForm,
    ElseEditPleaseBuyForm
  },
  data() {
    return {
      showTrue:'',
      userName: this.$store.getters.nickName,
      title: "请购明细记录",
      open: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      rows: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售信息管理表格数据
      dataList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        mainId: null,
        projectId: null,
        params: {},
        gongchengName: null,
        deliveryTime: null,
        goodsName: null,
        goodsCode: null,
        goodModel: null,
        /*orderByColumn: 'idx',
        isAsc: 'asc',*/
      },
      selectedRows:[],
      url: {
        listQinggouAll: '/goodsSaledo/goodsSaledo/listQinggouAll',//查询数量不是0的
        export: '/goodsSaledo/goodsSaledo/exportByPleaseBuy',
      },
      PrjNameOptions: [],
      tableMaxHeight: window.innerHeight - 0,
      editOpen: false, // 添加 editOpen 属性
      editFormData: {},
    };
  },
  created() {
    //window.addEventListener('resize', this.getTableHeight);
  },
  destroyed() {
    //window.removeEventListener('resize', this.getTableHeight)
  },
  methods: {
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      deleteAction('goodsSaledo/goodsSaledo/', ids).then(response => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    handleSubmitToKuguan(row) {
      const data = row;
      data.status = '38';
      updateAction('/goodsSaledo/goodsSaledo/edit', data).then(response => {
            this.$modal.msgSuccess("退回成功");
            this.editOpen = false;
            this.getList();
            this.$emit('ok');
        });
    },
    handleSubmitToLvyue(row){
      updateAction('/goodsSaledo/goodsSaledo/editToLvyue', row).then(response => {
        this.$modal.msgSuccess("退回成功");
        this.editOpen = false;
        this.getList();
        this.$emit('ok');
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    totalOutYear(param) {
      const {columns, data} = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        // 只合计amount1和amount3，想合并哪些列就在这里指定
        if ( column.property === "orderCount" || column.property === "pleaseBuyCount") {

          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev , curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },
    /** 删除按钮操作 */
    showDoList(row,show) {
      this.showTrue = show
      this.rows = row;
      let that = this;
      that.queryParams.mainId = row.id;
      // that.queryParams.projectId = row.mainId;
      that.getList();
      that.open = true;
      that.title="请购明细记录（ "+row.nos+" ）";
    },
    getTableHeight() {
      this.tableHeight = window.innerHeight - 320
    },
    /** 查询销售信息管理列表 */
    getList() {
      this.loading = true;
      getAction(this.url.listQinggouAll, this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.handleQuery();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 导出按钮操作 */
    handleExport() {
      downloadFile(this.url.export, this.queryParams);
    },
    handleEdit(row) {
      this.$refs.EditPleaseBuyFormList.open(row);
    },
    elseHandleEdit(row) {
      this.$refs.ElseEditPleaseBuyFormList.opens(row);
    },
  }
};
</script>
